package red.yancloud.www.ui.fragment


import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import red.yancloud.www.R
import red.yancloud.www.base.BaseFragment
import red.yancloud.www.common.Constants
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.ReadBook
import red.yancloud.www.internet.bean.ReadBookType
import red.yancloud.www.internet.bean.TypeData
import red.yancloud.www.ui.activity.BookInfoActivity
import red.yancloud.www.ui.adapter.GridSpacingItemDecoration
import red.yancloud.www.ui.adapter.ReadBookRecyclerAdapter
import red.yancloud.www.ui.adapter.TypeRecyclerAdapter
import red.yancloud.www.util.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/5 15:02
 * E_Mail：yh131412hys@163.com
 * Describe：阅读
 * Change：
 * @Version：V1.0
 */
class ReadFragment : BaseFragment() {

    private val TAG = "ReadFragment"

    private var selectPosition = -1//用于记录用户选择的变量
    private var typeId=""
    private lateinit var mReadFragmentSearchEt: AppCompatEditText
    private lateinit var mReadFragmentTypeRV: RecyclerView
    private lateinit var mReadFragmentBookRV: RecyclerView
    private lateinit var smartRefreshLayout: SmartRefreshLayout
    private lateinit var errorTv: AppCompatTextView
    private lateinit var mViewLoadFail: LinearLayoutCompat

    private lateinit var mTypeAdapter :TypeRecyclerAdapter
    private lateinit var readBookRecyclerAdapter:ReadBookRecyclerAdapter
    private var page: Int = 1
    private var totalPage: Int = 0
    private var keyword:String=""

    override val layoutId: Int
        get() = R.layout.fragment_read

    override fun attachView() {
    }

    override fun initData() {

        getBookList()
    }

    override fun configView() {

        mReadFragmentSearchEt = parentView.findViewById(R.id.readFragment_search_et)
        mReadFragmentTypeRV = parentView.findViewById(R.id.readFragment_type_rV)
        mReadFragmentBookRV = parentView.findViewById(R.id.readFragment_book_rV)
        smartRefreshLayout = parentView.findViewById(R.id.smartRefreshLayout)
        errorTv = parentView.findViewById<AppCompatTextView>(R.id.empty_view_tv)
        mViewLoadFail = parentView.findViewById(R.id.errorView)

        if (!NetworkUtils.isConnected(mContext)) {
            mViewLoadFail.visibility = View.VISIBLE
            errorTv.setText(R.string.no_network_view_hint)
            ToastUtils.toastNetErrorMsg()
            return
        }

        initSearchEditText()
        initRecyclerView()
        initSmartRefreshLayout()
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        mReadFragmentSearchEt.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId==EditorInfo.IME_ACTION_SEARCH) {

                    activity?.let { AppUtils.closeInoutDecorView(it) }

                    keyword = mReadFragmentSearchEt.text.toString().trim()
                    mReadFragmentSearchEt.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    getSearchBookList()
                    keyword=""
                    return true
                }
                return false
            }
        })
    }

    /**
     * 书籍搜索
     */
    private fun getSearchBookList() {

        loadingDialog.show()
        page=1
        typeId = ""
        mTypeAdapter.setSelectPosition(-1)
        mReadFragmentTypeRV.scrollToPosition(0)
        mReadFragmentTypeRV.scrollBy(1,0)
        mReadFragmentTypeRV.scrollBy(-1,0)
        RedCloudApis.getInstance().getSearchBookList(typeId, keyword, page.toString(), "10", object : Observer<ResponseBody> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: ResponseBody) {

                val result = String(t.bytes())
                Log.d(TAG, result)
                val jsonObject = JSONObject.parseObject(result)
                val code = jsonObject.getString("code")

                if (code==Constants.SYSTEM_OK) {

                    mViewLoadFail.visibility=View.GONE
                    smartRefreshLayout.visibility=View.VISIBLE

                    val readBookEntity = JSONObject.parseObject(result, ReadBook::class.java)
                    if(readBookEntity.data != null&&readBookEntity.data.page!=null&& readBookEntity.data.books != null && readBookEntity.data.books.size > 0){

                        totalPage = readBookEntity.data.page.totalPage
                        if (page==1) {

                            readBookRecyclerAdapter.data.clear()
                            readBookRecyclerAdapter.addData(readBookEntity.data.books)
                            smartRefreshLayout.resetNoMoreData()
                            smartRefreshLayout.finishRefresh()

//                            处理数据加载后，页面刷新异常问题
                            mReadFragmentBookRV.scrollBy(1,0)
                            mReadFragmentBookRV.scrollBy(-1,0)
                        }else {

                            readBookRecyclerAdapter.addData(readBookEntity.data.books)
                            smartRefreshLayout.finishLoadMore()
                        }
                    }else{

                        if (page==1){

                            mViewLoadFail.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                            smartRefreshLayout.finishRefresh()
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            smartRefreshLayout.finishLoadMore()
                        }
                    }

                    loadingDialog.dismiss()
                }else{

                    ToastUtils.showToast(jsonObject.getString("msg"))
                    mViewLoadFail.visibility=View.VISIBLE
                    smartRefreshLayout.visibility=View.GONE

                    loadingDialog.dismiss()
                }
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
            }
        })
    }

    private fun initRecyclerView() {

        val typeList = ArrayList<TypeData>()

        mReadFragmentTypeRV.layoutManager=LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false)
        mTypeAdapter = TypeRecyclerAdapter(R.layout.item_read_type_list)
        mReadFragmentTypeRV.adapter= mTypeAdapter
        mTypeAdapter.onItemClickListener = object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                //获取选中的参数
                selectPosition = position
                mTypeAdapter.setSelectPosition(selectPosition)

                //                处理数据不刷新问题
//                mReadFragmentTypeRV.scrollTo(1,0)
                mReadFragmentTypeRV.scrollBy(1,0)
                mReadFragmentTypeRV.scrollBy(-1,0)
                page=1
                typeId = typeList[position].typeId
                mReadFragmentBookRV.scrollToPosition(0)
                getBookList()
            }
        }

        RedCloudApis.getInstance().bookConfig(object : Observer<ReadBookType> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: ReadBookType) {

                Log.d(TAG, t.data.toString())

                if (t.code == Constants.SYSTEM_OK && t.data!=null) {

//                    取消全部
                    typeList.add(TypeData("全部",""))
//                    typeId = t.data[0].id
//                    getBookList()
                    for (i in 0 until t.data.size) {

                        typeList.add(TypeData(t.data[i].title,t.data[i].id))
                    }

                    Log.d(TAG, typeList.toString())

                    mTypeAdapter.addData(typeList)

                    mReadFragmentTypeRV.scrollBy(1,0)
                    mReadFragmentTypeRV.scrollBy(-1,0)
                }
            }

            override fun onError(e: Throwable) {
            }
        })

        mReadFragmentBookRV.layoutManager=GridLayoutManager(mContext,2,RecyclerView.VERTICAL,false)
//        mReadFragmentBookRV.addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL))
//        mReadFragmentBookRV.addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL))
        mReadFragmentBookRV.addItemDecoration(GridSpacingItemDecoration(2,ScreenUtils.dip2px(mContext,10f),false))
        readBookRecyclerAdapter = ReadBookRecyclerAdapter(R.layout.item_read_book_list)
        mReadFragmentBookRV.adapter= readBookRecyclerAdapter
        readBookRecyclerAdapter.onItemClickListener = object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                startActivity(
                    Intent(mContext, BookInfoActivity::class.java)
                        .putExtra("bookId",(adapter!!.data[position] as ReadBook.DataBean.BooksBean).id)
                        .putExtra(
                            "url",
                            "${Constants.API_BASE_RED_CLOUD_URL}article/?bid=${(adapter.data[position] as ReadBook.DataBean.BooksBean).id}"
                        )
                )
            }
        }
    }

    private fun getBookList() {

        loadingDialog.show()

        RedCloudApis.getInstance().bookList(
            UserInfoShardPreference.instance.uid,
            page.toString(),
            "10",
            typeId,
            object : Observer<ResponseBody> {

                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ResponseBody) {

//                    Log.d(TAG, t.data.toString())

                    val result = String(t.bytes())
                    Log.d(TAG, result)
                    val jsonObject = JSONObject.parseObject(result)
                    val code = jsonObject.getString("code")

                    if (code==Constants.SYSTEM_OK) {

                        mViewLoadFail.visibility=View.GONE
                        smartRefreshLayout.visibility=View.VISIBLE

                        val readBookEntity = JSONObject.parseObject(result, ReadBook::class.java)
                        if(readBookEntity.data != null&&readBookEntity.data.page!=null&& readBookEntity.data.books != null && readBookEntity.data.books.size > 0){

                            totalPage = readBookEntity.data.page.totalPage
                            if (page==1) {

                                readBookRecyclerAdapter.data.clear()
                                readBookRecyclerAdapter.addData(readBookEntity.data.books)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()

                                mReadFragmentBookRV.scrollBy(1,0)
                                mReadFragmentBookRV.scrollBy(-1,0)
                            }else {

                                readBookRecyclerAdapter.addData(readBookEntity.data.books)
                                smartRefreshLayout.finishLoadMore()
                            }
                        }else{

                            if (page==1){

                                smartRefreshLayout.finishRefresh()

                                mViewLoadFail.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                            }else{

                                ToastUtils.showToast(getString(R.string.data_all_load))
                                smartRefreshLayout.finishLoadMore()
                            }
                        }

                    }else{

                        ToastUtils.showToast(jsonObject.getString("msg"))
                        mViewLoadFail.visibility=View.VISIBLE
                        smartRefreshLayout.visibility=View.GONE
                    }

                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    loadingDialog.dismiss()
                }
            })
    }

    private fun initSmartRefreshLayout() {

//        smartRefreshLayout.autoRefresh()

        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))
        /*Translate, //平行移动        特点: HeaderView高度不会改变，
            Scale, //拉伸形变            特点：在下拉和上弹（HeaderView高度改变）时候，会自动触发OnDraw事件
            FixedBehind, //固定在背后    特点：HeaderView高度不会改变，
            FixedFront, //固定在前面     特点：HeaderView高度不会改变，
            MatchLayout//填满布局        特点：HeaderView高度不会改变，尺寸充满 RefreshLayout*/
//        mClassicsHeader.spinnerStyle = SpinnerStyle.Scale

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(mContext)) {
                mViewLoadFail.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            page=1
            getBookList()
        })
        smartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->

            if (page>=totalPage){

                ToastUtils.showToast(getString(R.string.data_all_load))
                smartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
                return@OnLoadMoreListener
            }

            if (!NetworkUtils.isConnected(mContext)) {
                mViewLoadFail.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishLoadMore()
                return@OnLoadMoreListener
            }
            page++
            getBookList()
        })
    }
}
